var bg = chrome.extension.getBackgroundPage();
var baseurl = "http://" + bg.Options.Domain.Current + "/";
var activeTabId;
var initStatus = 
{
	NewMessages : "pending", 
	SimpleRead: "pending", 
};
var simpleread_container = document.getElementById("simpleread_container");

function init_done()
{
	if(initStatus.NewMessages == "none" && initStatus.SimpleRead == "none")
		chrome.tabs.create({url: baseurl});
}

bg.ReadNewMessages(function(messages)
{
	var table = document.getElementById("new_messages");
	var tbody = table.children[0];
	if(messages && messages.length)
	{
		table.style.display = "";
		initStatus.NewMessages = "done";
	}
	else
		initStatus.NewMessages = "none";
	for(var i = 0; i < messages.length; ++i)
	{
		var cur = messages[i];
		var tr = document.createElement("tr");
		var fromUser = document.createElement("td");
		var fromUser_link = document.createElement("a");
		var title = document.createElement("td");
		var title_link = document.createElement("a");
		var time = document.createElement("td");
		fromUser_link.href = baseurl + "u.php?action=show&uid=" + cur.fromUid;
		fromUser_link.target = "_blank";
		fromUser_link.appendChild(document.createTextNode(cur.fromUser));
		title_link.href = baseurl + "message.php?action=" + cur.actionId + "&mid=" + cur.id;
		title_link.target = "_blank";
		title_link.appendChild(document.createTextNode(cur.title));
		fromUser.style.textAlign = "center";
		fromUser.appendChild(fromUser_link);
		title.appendChild(title_link);
		time.style.textAlign = "center";
		time.appendChild(document.createTextNode(cur.time));
		tr.appendChild(fromUser);
		tr.appendChild(title);
		tr.appendChild(time);
		tbody.appendChild(tr);
	}
	init_done();
});

chrome.windows.getLastFocused(null, function(curWindow)
{
	function init(tab)
	{
		activeTabId = tab.id;
		if(tab.url)
		{
			if(tab.url.indexOf(baseurl + "read.php") == 0)
			{
				simpleread_container.style.display = "";
				initStatus.SimpleRead = "done";
			}
			else
				initStatus.SimpleRead = "none";
		}
		init_done();
	}
	if(!curWindow)
		return;
	if(chrome.tabs.query)
	{
		chrome.tabs.query({windowId: curWindow.id, active: true}, function(tabs)
		{
			tabs && tabs[0] && init(tabs[0]);
		});
	}
	else
		chrome.tabs.getSelected(curWindow.id, function(tab)
		{
			tab && init(tab);
		});
});

var simpleread = document.getElementById("simpleread");
simpleread.checked = bg.Options.UI.SimpleRead;
simpleread.onchange = (function()
{
	bg.Options.UI.SimpleRead = this.checked;
	activeTabId && chrome.tabs.reload(activeTabId);
});

